package com.ngmaster.socket.util;

import okhttp3.*;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * http的常用方法
 * Get
 * Post
 * */
public class HttpRequestUtil {

    public static void asyncPost(String url, RequestBody requestBody) {
        asyncPost(url, DoNothingCallback.DO_NOTHING_CALLBACK, requestBody);
    }


    /**
     * 异步POST
     * @param url post的url地址
     * @param callback post的回调函数，主要是post失败和成功的回调
     * @param requestBody post提交的内容
     * */
    public static void asyncPost(String url, Callback callback, RequestBody requestBody) {
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(callback);
    }

    public static void asyncGet(String url, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * 异步post
     * @param url post的url地址
     * @param callback post的回调函数，主要是post失败和成功的回调
     * @param postBody post的消息体
     * */
    public static void asyncPost(String url, Callback callback, LinkedHashMap<String, String> postBody, String appSecure) {
        FormBody.Builder builder = new FormBody.Builder();
        if (postBody != null) {
            for (Map.Entry<String, String> entry : postBody.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        String sign = SignUtil.sign(postBody, appSecure);
        builder.add("sign", sign);
        asyncPost(url, callback, builder.build());
    }

    /**
     * 异步post，不关心请求结果
     * @param url post的url地址
     * @param formBody post的消息体
     * */
    public static void asyncPost(String url, FormBody formBody) {
        asyncPost(url, DoNothingCallback.DO_NOTHING_CALLBACK, formBody);
    }

    /**
     * 异步post，不关心请求结果
     * @param url post的url地址
     * @param postBody post的消息体
     * */
    public static void asyncPost(String url, LinkedHashMap<String, String> postBody, String appSecure) {
        asyncPost(url, DoNothingCallback.DO_NOTHING_CALLBACK, postBody, appSecure);
    }
}
